//index.js
//获取应用实例
const app = getApp()
let Compress = require('../../common/js/compressImage.js'); //引入Axios方法
let Axios = require('../../common/js/ajax.js'); //引入Axios方法
let Mtils = require('../../common/js/Mtils.min.js');
let WxValidate = require('../../common/js/WxValidate.js'); //表单验证
Mtils = Mtils.Mtils
Page({
	data: {
		openid: '',
		nickName: '',
		avatarUrl: '',
		canvasWidth: 0,
		canvasHeight: 0,
		curentNav: 2, //当前导航
		mainVideo: '',
		moreVideo: '',
		poster: '',
		imgList: [],
		moreImg: [],
		posterFlag: false,
		model: false,
		cur_menu: 1,
		neatness: 0,
		level: 0,
		cur_video: 0,
		vpause: false, //视频加载完成的判断
		master_pictures: [],
		sub_pictures: [],
		del_sub_picture_id: [],
		del_master_picture_id: [],
		goods_id:'',
		good: {}
	},
	//事件处理函数
	onLoad: function(e) {	
		this.uid = app.globalData.uid || ''
		this.Md5 = Mtils.security.hex_md5(this.uid) + app.globalData.secret;
		this.Md5 = Mtils.security.hex_md5(this.Md5);
		this.timesp = Mtils.now();
		var _this = this
		this.load = this.selectComponent("#loading");
		if(e.id){
			this.setData({
				goods_id:e.id
			})
		}else{
			_this.load.loadIng()
		}
		Axios.get(app.globalData.baseUrl + 'App/Store/Goods/edit_goods', { //关键字
			uid: _this.uid,
			time: _this.timesp,
			sign: _this.Md5,
			goods_id: _this.data.goods_id
		}, (res) => {
			console.log(res)
			if (res.status == 1) {
				var data = res.info
				_this.setData({
					good: data
				},function(){
					_this.load.loadIng()
					console.log(_this.data.good)
					_this.initValidate()	
				})
					
			} else {
				_this.showModal(error)
			}
		})
	},
	onReady: function() {
		wx.setNavigationBarTitle({
			title: '发布商品'
		})
	},
	chooseImage: function(e) {
		var _this = this
		var index = e.currentTarget.dataset.type
		var type = ['album', 'camera'];
		var temporaryImg = []
		this.setData({
			compress:true
		})
		wx.chooseImage({
			sizeType: ['original', 'compressed'], //可选择原图或压缩后的图片
			sourceType: type, //可选择性开放访问相册、相机
			success: function(res) {
				wx.showLoading({
					title: '正在上传中',
				})
				temporaryImg = res.tempFilePaths
				d_gui()
			}
		})

		function d_gui() {
			var i = 0
			wx.getImageInfo({
				src: temporaryImg[i],
				success: function(res) {
					var ctx = wx.createCanvasContext('photo_canvas');
					var ratio = 2;
					var canvasWidth = res.width
					var canvasHeight = res.height;
					// 保证宽高均在200以内
					//console.log(canvasWidth)
					if (res.width > res.height) {
						canvasHeight = res.height * (750 / res.width)
						canvasWidth = 750
					} else if (res.height > res.width) {
						canvasWidth = res.width * (1366 / res.height)
						canvasHeight = 1366
					} else {
						while (canvasWidth > 750 || canvasHeight > 1336) {
							//比例取整
							canvasWidth = Math.trunc(res.width / ratio)
							canvasHeight = Math.trunc(res.height / ratio)
							ratio++;
						}
					}
					_this.setData({
						canvasWidth: canvasWidth,
						canvasHeight: canvasHeight
					}) //设置canvas尺寸
					ctx.drawImage(temporaryImg[i], 0, 0, canvasWidth, canvasHeight) //将图片填充在canvas上
					ctx.draw()
					//下载canvas图片				
					setTimeout(function() {
						wx.canvasToTempFilePath({
							canvasId: 'photo_canvas',
							success: function(res) {
								//console.log(res.tempFilePath)	
								wx.uploadFile({
									url: app.globalData.baseUrl + 'App/PublicCommon/Public/UploadPicture',
									filePath: res.tempFilePath,
									name: 'file',
									formData: {
										uid: _this.uid,
										sign: _this.Md5,
										time: _this.timesp
									},
									success: function(res) {
										var data = JSON.parse(res.data) //坑2：与wx.request不同，wx.uploadFile返回的是[字符串]，需要自己转为JSON格式
										var info = data.info
										if (data.status == 1) {
											if (index == 0) {
												let images = _this.data.good.master_pictures
												var obj = {}
												obj.id = 0
												obj.cover = info.save_path
												images.push(obj)
												images = images.length <= 9 ? images : images.slice(0, 9)
												_this.setData({
													'good.master_pictures': images
												})
											} else {
												let images = _this.data.good.sub_pictures;
												var obj = {}
												obj.id = 0
												obj.cover = info.save_path
												images.push(obj)
												images = images.length <= 9 ? images : images.slice(0, 9)
												_this.setData({
													'good.sub_pictures': images
												})
											}
											temporaryImg.splice(0, 1)
											if (temporaryImg.length > 0) {
												d_gui()
											}else{
												wx.hideLoading();
												_this.setData({
													compress:false
												})
											}
										}
									}
								})
							},
							fail: function(error) {
								console.log(error)
							}
						})
					}, 100)
				},
				fail: function(error) {
					console.log(error)
				}
			})
		}
	},
	handleVideoTap: function(e) {
		var _this = this
		var index = e.currentTarget.dataset.type
		wx.chooseVideo({
			sourceType: ['camera'],
			maxDuration: 60,
			camera: 'back',
			success: function(res) {
				console.log(res)
				console.log(res.thumbTempFilePath)
				var limit = res.size;
				var size = (limit / (1024 * 1024)).toFixed(2) + "MB";
				if (size > '2MB') {
					wx.showModal({
						content: '视频不能超过2M,重新上传',
						showCancel: false,
					})
					return false
				}
				wx.uploadFile({
					url: app.globalData.baseUrl + 'App/PublicCommon/Public/UploadVideo',
					filePath: res.tempFilePath,
					name: 'file',
					formData: {
						uid: _this.uid,
						sign: _this.Md5,
						time: _this.timesp
					},
					success: function(res) {
						var data = JSON.parse(res.data)
						console.log(data)
						var info = data.info;
						if (data.status == 1) {
							if (index == 0) {
								_this.setData({
									'good.head_video': info.save_video_path,
									'good.head_video_picture': info.save_path
								})
							} else {
								_this.setData({
									'good.detail_video': info.save_video_path,
									'good.detail_video_picture': info.save_path
								})
							}
						}
					}
				})
			}
		})
	},
	videoPlay: function(e) { //视频播放
		var id = e.currentTarget.dataset.id
		this.setData({
			cur_video: id,
			vpause: false,
		})
		this.videoContext = wx.createVideoContext('myVideo' + id)
		this.videoContext.requestFullScreen({direction: 90});
		this.videoContext.play();
	},
	videoPause: function() { //监听视频暂停
		if (this.data.vpause) {
			this.setData({
				cur_video: 0,
			})
		}
	},
	vwait: function() { //判断视频是否加载完成
		this.setData({
			vpause: true,
		})
	},
	deleteFunc: function(e) {
		var _this = this
		var id = e.currentTarget.dataset.id
		var index = e.currentTarget.dataset.index
		var type = e.currentTarget.dataset.type;
		if (type == 0) {
			var images = this.data.good.master_pictures
			images.splice(index, 1)
			var temp = this.data.del_master_picture_id
			temp.push(id)
			_this.setData({
				'good.master_pictures': images,
				del_master_picture_id: temp
			})
			//console.log(this.data.good.master_pictures)
	
		} else {
			var images = this.data.good.sub_pictures
			images.splice(index, 1)
			var temp = this.data.del_sub_picture_id
			temp.push(id)
			_this.setData({
				'good.sub_pictures': images,
				del_sub_picture_id: temp
			})			
		}
	},
	handlePostTap: function() {
		var _this = this
		_this.setData({
			'good.is_head_video': !_this.data.good.is_head_video
		})
		_this.initValidate()	
	},
	handleModelTap: function() {
		var _this = this
		_this.setData({
			model: !_this.data.model
		})
	},
	handleMenuTap: function(e) {
		var id = e.currentTarget.dataset.id;
		var index = e.currentTarget.dataset.index;
		this.setData({
			cur_menu: id
		})
	},
	handleNeatness: function(e) {
		var index = e.currentTarget.dataset.index;
		var tempIndex = e.currentTarget.dataset.temp;
		var value = e.currentTarget.dataset.value;
		console.log(value)
		this.setData({
			['good.template[' + tempIndex + '].settings[' + index + '].value']: value
		})
	},
	handleLevel: function(e) {
		var id = e.currentTarget.dataset.id;
		this.setData({
			level: id
		})
	},
	submit: function(e) {
		var _this = this	
		var o_mast = _this.data.master_pictures
		this.data.good.master_pictures.forEach(function(item,key){
			if(item.id == 0){
				o_mast.push(item.cover)
			}
		})
		var o_sub = _this.data.sub_pictures
		this.data.good.sub_pictures.forEach(function(item,key){		
			if(item.id == 0){
				o_sub.push(item.cover)
			}	
		})
		this.setData({
			master_pictures:o_mast,
			sub_pictures:o_sub
		})
		e.detail.value.master_pictures = _this.data.master_pictures
		e.detail.value.sub_pictures = _this.data.sub_pictures
		var params = e.detail.value
		if (!this.WxValidate.checkForm(params)) {
			const error = this.WxValidate.errorList[0]
			this.showModal(error)
			return false
		}
		this.submitInfo(params);
	},
	submitInfo: function(e) {
		var _this = this
		e.uid = this.uid;
		e.time = this.timesp;
		e.sign = this.Md5;
		Axios.post(app.globalData.baseUrl + 'App/Store/Goods/edit_goods', e, (res) => {
			console.log(res)
			if (res.status == 1) {
				var data = res.info
				wx.showModal({
					content: '保存成功',
					showCancel: false,
					success:function(){
						wx.navigateTo({
							url:'/pages/goodDetail/goodDetail?id='+res.info
						})
					}
				})			
			}else{
				_this.showModal(res)
			}
		})
	},
	showModal: function(error) {
		wx.showModal({
			content: error.msg,
			showCancel: false,
		})
	},
	initValidate: function() {
		/** 4-2(配置规则)*/
		console.log(this.data.good.is_head_video)
		if(this.data.good.is_head_video == 1){
			var rules = {
				title: {
					required: true,
					rangelength: [1, 60]
				},
				stock: {
					required: true
				},
				// 配置false可关闭验证
				price: {
					required: true
				},
				tempmaster_pictures: {
					required: false,
				},
				head_video: {
					required: true,
				},
			}				
		}else{
			var rules = {
				title: {
					required: true,
					rangelength: [1, 60]
				},
				stock: {
					required: true
				},
				// 配置false可关闭验证
				price: {
					required: true
				},
				tempmaster_pictures: {
					required: true,
				},
				head_video: {
					required: false,
				},
			}		
			console.log(rules)
		}
		console.log(rules)
			// 验证字段的提示信息，若不传则调用默认的信息
		const messages = {
			title: {
				required: '请输入宝贝标题',
				rangelength: '最多60个字'
			},
			stock: {
				required: '请输入库存',
			},
			price: {
				required: '请输入价格',
			},
			tempmaster_pictures: {
				required: '请上传主图',
			},
			head_video: {
				required: '请上传主视频'
			},
		}
		// 创建实例对象
		this.WxValidate = new WxValidate.WxValidate(rules, messages)
		/**
		 * 也可以自定义验证规则
		 */
		// 		this.WxValidate.addMethod('assistance', (value, param) => {
		// 			return this.WxValidate.optional(value) || (value.length >= 1 && value.length <= 2)
		// 		}, '请勾选 《顺风男服务协议》')
	}
})
